package models

import (
	"encoding/json"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// CouponActivity 优惠活动模型
type CouponActivity struct {
	BaseModel
	Name           string  `orm:"size(100)" json:"name"`                         // 活动名称
	Type           int     `orm:"" json:"type"`                                  // 活动类型：discount(折扣)、amount(满减)、gift(满赠)、coupon(优惠券)
	Description    string  `orm:"size(500)" json:"description"`                  // 活动描述
	StartTime      int64   `orm:"" json:"start_time"`                            // 开始时间
	EndTime        int64   `orm:"" json:"end_time"`                              // 结束时间
	MinAmount      float64 `orm:"digits(10);decimals(2)" json:"min_amount"`      // 最低消费金额
	DiscountAmount float64 `orm:"digits(10);decimals(2)" json:"discount_amount"` // 优惠金额（满减）
	DiscountRate   float64 `orm:"digits(10);decimals(2)" json:"discount_rate"`   // 折扣率（折扣）
	CouponIds      string  `orm:"size(500)" json:"coupon_ids"`                   // 关联的优惠券ID，JSON格式存储
	Status         int     `orm:"" json:"status"`                                // 状态：active(启用)、inactive(禁用)
	ApplicableType    int8   `orm:"default(0)" json:"applicable_type"`             // 0:全场通用, 1:指定门店, 2:指定包厢
	ApplicableIds     string `orm:"size(1000)" json:"applicable_ids"`              // 适用的门店或包厢ID，JSON格式存储
	AvailableWeekdays string `orm:"size(255)" json:"available_weekdays"` // 可用星期, JSON array
	AvailableTimes    string `orm:"size(1000)" json:"available_times"`   // 可用时段, JSON array of time ranges
}

// TableName 设置表名
func (c *CouponActivity) TableName() string {
	return "ss_coupon_activity"
}

// GetCouponActivityById 根据ID获取优惠活动信息
func GetCouponActivityById(id int64) (*CouponActivity, error) {
	activity := &CouponActivity{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(activity)
	return activity, err
}

// GetCouponActivityList 获取优惠活动列表
func GetCouponActivityList(page, pageSize int, filters map[string]interface{}) ([]*CouponActivity, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(CouponActivity))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if activityType, ok := filters["type"].(int); ok && activityType >= 0 {
		qs = qs.Filter("type", activityType)
	}

	if status, ok := filters["status"].(int); ok && status >= 0 {
		qs = qs.Filter("status", status)
	}

	// 开始时间过滤
	if startTime, ok := filters["start_time"].(int64); ok && startTime > 0 {
		qs = qs.Filter("start_time__gte", startTime)
	}

	if startTimeLte, ok := filters["start_time_lte"].(int64); ok && startTimeLte > 0 {
		qs = qs.Filter("start_time__lte", startTimeLte)
	}

	if startTimeGt, ok := filters["start_time_gt"].(int64); ok && startTimeGt > 0 {
		qs = qs.Filter("start_time__gt", startTimeGt)
	}

	// 结束时间过滤
	if endTime, ok := filters["end_time"].(int64); ok && endTime > 0 {
		qs = qs.Filter("end_time__lte", endTime)
	}

	if endTimeGte, ok := filters["end_time_gte"].(int64); ok && endTimeGte > 0 {
		qs = qs.Filter("end_time__gte", endTimeGte)
	}

	if endTimeLt, ok := filters["end_time_lt"].(int64); ok && endTimeLt > 0 {
		qs = qs.Filter("end_time__lt", endTimeLt)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var activities []*CouponActivity
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&activities)

	return activities, total, err
}

// CreateCouponActivity 创建优惠活动
func CreateCouponActivity(activity *CouponActivity) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(activity)
	return id, err
}

// UpdateCouponActivity 更新优惠活动信息
func UpdateCouponActivity(activity *CouponActivity, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(activity, fields...)
	return err
}

// DeleteCouponActivity 删除优惠活动（软删除）
func DeleteCouponActivity(id int64) error {
	o := orm.NewOrm()
	activity := &CouponActivity{BaseModel: BaseModel{Id: id}}
	if err := o.Read(activity); err != nil {
		return err
	}

	activity.IsDeleted = 1
	_, err := o.Update(activity, "IsDeleted")
	return err
}

// GetActiveActivities 获取当前有效的活动列表
func GetActiveActivities() ([]*CouponActivity, error) {
	o := orm.NewOrm()
	var activities []*CouponActivity
	now := time.Now().Unix()
	_, err := o.QueryTable(new(CouponActivity)).
		Filter("status", "active").
		Filter("is_deleted", 0).
		Filter("start_time__lte", now).
		Filter("end_time__gte", now).
		All(&activities)
	return activities, err
}

// GetCouponsByActivityId 获取活动关联的优惠券
func GetCouponsByActivityId(id int64) ([]*Coupon, error) {
	activity, err := GetCouponActivityById(id)
	if err != nil {
		return nil, err
	}

	if activity.Type != 3 || activity.CouponIds == "" {
		return nil, nil
	}

	var couponIds []int64
	err = json.Unmarshal([]byte(activity.CouponIds), &couponIds)
	if err != nil {
		return nil, err
	}

	if len(couponIds) == 0 {
		return nil, nil
	}

	o := orm.NewOrm()
	var coupons []*Coupon
	_, err = o.QueryTable(new(Coupon)).
		Filter("id__in", couponIds).
		Filter("is_deleted", 0).
		All(&coupons)

	return coupons, err
}
